//
//  ImageDownloaderQueue.m
//  ImageFinder
//
//  Created by Chris Greening on 20/03/2010.
//  Copyright 2010 CMG Research. All rights reserved.
//

#import "ImageDownloaderQueue.h"
#import "ProgramInfo.h"

@implementation ImageDownloaderQueue

- (id) init
{
	self = [super init];
	if (self != nil) {
		queue=[[NSMutableArray alloc] init];
	}
	return self;
}

- (void) dealloc
{
	[queue release];
	[downloader cancelDownload];
	[downloader release];
	[super dealloc];
}

-(void) startDownload {
	if(queue.count>0) {
		ProgramInfo *imageToDownload=[queue objectAtIndex:0];
		downloader=[[HttpDownloader alloc] init];
		[downloader downloadDataFromUrl:imageToDownload.thumbnailUrl delegate:self];
	}
}

-(void) downloader:(HttpDownloader *) theDownloader downloadedData:(NSData *) data {
	ProgramInfo *imageToDownload=[queue objectAtIndex:0];
	imageToDownload.tableCell.imageView.image=[UIImage imageWithData:data];
	imageToDownload.thumbnailDownloaded=true;
	[imageToDownload.tableCell setNeedsLayout];
	[queue removeObjectAtIndex:0];
	[downloader release];
	downloader=nil;
	[self startDownload];
}

-(void) downloaderFailed:(HttpDownloader *) theDownloader {
	ProgramInfo *imageToDownload=[queue objectAtIndex:0];
	imageToDownload.tableCell.imageView.image=[UIImage imageNamed:@"broken.png"];
	imageToDownload.thumbnailDownloaded=true;
	[queue removeObjectAtIndex:0];
	[downloader release];
	downloader=nil;
	[self startDownload];
}

-(void) downloadImage:(ProgramInfo *) imageToDownload {
	if(!imageToDownload.thumbnailDownloaded) {
		[queue addObject:imageToDownload];
		if(queue.count==1) {
			[self startDownload];
		}
	}
}

-(void) cancelAll {
	[downloader cancelDownload];
	[downloader release];
	downloader=nil;
	[queue removeAllObjects];
}

-(bool) running {
	return queue.count>0;
}


@end
